package work.io.aio.server;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class MyCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,Server> {



    //Socket
    @Override
    public void completed(AsynchronousSocketChannel result, Server attachment) {

        //为下次请求做准备,给下次请求放入一个令牌
        attachment.getChannel().accept(attachment, this);

        read(result);

      //  throw new RuntimeException("模拟出现异常");

    }

    @Override
    public void failed(Throwable exc, Server attachment) {
            exc.printStackTrace();
    }


    private void read(AsynchronousSocketChannel r) {

        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //这里是线程异步的操作
        r.read(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {//这里的读取总是异步的
            @Override
            public void completed(Integer result, ByteBuffer attachment) {

                //获取容量
                System.out.println("容量:" + attachment.capacity());

                //打印结果
                System.out.println("内容:" + new String(attachment.array(), 0, result));

            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {

            }
        });

    }


    private void write() {

    }






}
